﻿using System;
using System.Net;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using System.Linq;
using NjamNjamAdminApp.Models;

namespace NjamNjamAdminApp.Views
{
    public partial class AddressSearchView : DevExpress.XtraEditors.XtraForm
    {
        private string m_Address;

        public AddressSearchView()
        {
            InitializeComponent();
            btnPretrazi.Click += (s, e) => OnPretrazi();
            btnIzaberi.Click += (s, e) =>
                                {
                                    SearchResult = searchResultBindingSource.Current as SearchResult;
                                    Close();
                                };
            btnOtkazi.Click += (s, e) =>
                               {
                                   SearchResult = null;
                                   Close();
                               };
            textEdit1.EditValueChanged += (s, e) =>
                                          {
                                              m_Address = textEdit1.Text;
                                          };
            textEdit1.KeyDown += (s, e) =>
                                 {
                                     if (e.KeyCode == Keys.Enter)
                                     {
                                         OnPretrazi();
                                     }
                                 };
        }

        public AddressSearchView(string address)
            : this()
        {
            m_Address = address;
            textEdit1.EditValue = m_Address;
        }

        public SearchResult SearchResult { get; set; }

        private void OnPretrazi()
        {
            var wc = new WebClient();
            searchResultBindingSource.DataSource = typeof (SearchResult);
            wc.DownloadStringCompleted += OnDownloadCompleted;
            marqueeProgressBarControl1.Enabled = true;
            marqueeProgressBarControl1.Properties.ShowTitle = true;
            wc.DownloadStringAsync(new Uri("http://maps.googleapis.com/maps/api/geocode/json?address=" + m_Address + "&sensor=true", UriKind.Absolute), wc);
        }

        private void OnDownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                marqueeProgressBarControl1.Enabled = false;
                marqueeProgressBarControl1.Properties.ShowTitle = false;
                if (e.Error != null)
                {
                    return;
                }
                var result = JObject.Parse(e.Result);
                var sr = from r in result["results"].Children()
                         let address = r["formatted_address"].Value<string>()
                         let lat = r["geometry"]["location"]["lat"].Value<double>()
                         let lon = r["geometry"]["location"]["lng"].Value<double>()
                         select new SearchResult
                                {
                                    Address = address,
                                    Latitude = lat,
                                    Longitude = lon
                                };
                searchResultBindingSource.DataSource = sr;
            }
            finally
            {
                var client = (WebClient) e.UserState;
                client.Dispose();
            }

        }

        
    }
}